package com.aurora.oa.work.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.aurora.oa.R;
import com.aurora.oa.activity.BaseActivity;
import com.aurora.oa.application.MyApplication;
import com.aurora.oa.customview.ItemDivider;
import com.aurora.oa.customview.SelectPicPopupWindow;
import com.aurora.oa.message.adapter.ImageSelectAdapter;
import com.aurora.oa.utils.ToastUtil;
import com.aurora.oa.utils.UriUtils;
import com.aurora.oa.work.bean.AddExpenceData;
import com.aurora.oa.work.presenter.AddExpenceActivityPresenter;
import com.aurora.oa.work.presenter.AddExpenceActivityPresenterImpl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/3/29 0029.
 */
public class AddExpenceActivity extends BaseActivity implements AddExpenceActivityView{

    private static final int TAKE_PHOTO = 1 ;
    private static final int PICK_PHOTO = 2;
    private List<Uri> imageUri = new ArrayList<>();
    //文件上传成功服务器返回
    private List<String> uploadFileIDs;
    //自定义的弹出框类
    private SelectPicPopupWindow menuWindow;
    private ProgressDialog progressDialog;
    private ImageSelectAdapter imageSelectAdapter;
    private AddExpenceActivityPresenter presenter;
    private TextView tv_depart;
    private TextView tv_name;
    private TextView tv_duty;
    private EditText et_expence_type;
    private EditText et_expence_money;
    private EditText et_sell;
    private TextView tv_approve_status;
    private Button bt_submit;
    private RecyclerView rv_expence_tickets;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initTitlebar(true,"报销",true);
        setMyContentView(R.layout.activity_add_expence);
        initView();
        initData();
    }

    private void initData() {
        presenter = new AddExpenceActivityPresenterImpl(this);
        tv_name.setText(MyApplication.getInstance().getLoginUser().getRealname());
        tv_depart.setText(MyApplication.getInstance().getLoginUser().getDepartment());
        tv_duty.setText(MyApplication.getInstance().getLoginUser().getPostname());
        imageSelectAdapter = new ImageSelectAdapter(this,imageUri);
        imageSelectAdapter.setOnItemClickListener(new ImageSelectAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(position==imageUri.size()){
                    //选择图片
                    //实例化SelectPicPopupWindow
                    menuWindow = new SelectPicPopupWindow(AddExpenceActivity.this, itemsOnClick);
                    //显示窗口
                    menuWindow.showAtLocation(AddExpenceActivity.this.findViewById(R.id.main), Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                }
            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
        rv_expence_tickets.setAdapter(imageSelectAdapter);
        rv_expence_tickets.setLayoutManager(new GridLayoutManager(this,3));
        rv_expence_tickets.setItemAnimator(new DefaultItemAnimator());
        rv_expence_tickets.addItemDecoration(new ItemDivider().setDividerWith(3).setDividerColor(Color.TRANSPARENT));

        bt_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                presenter.sendExpence();
            }
        });
    }

    private void initView() {
        tv_depart = (TextView) findViewById(R.id.tv_depart);
        tv_name = (TextView) findViewById(R.id.tv_title);;
         tv_duty = (TextView) findViewById(R.id.tv_duty);
         et_expence_type = (EditText) findViewById(R.id.et_expence_type);
         et_expence_money = (EditText) findViewById(R.id.et_expence_money);
         et_sell = (EditText) findViewById(R.id.et_sell);
         tv_approve_status = (TextView) findViewById(R.id.tv_approve_status);
         rv_expence_tickets = (RecyclerView) findViewById(R.id.rv_expence_tickets);
        bt_submit = (Button) findViewById(R.id.bt_submit);
    }

    //为弹出窗口实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener(){

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, TAKE_PHOTO);
                    break;
                case R.id.btn_pick_photo:
                    Intent local = new Intent();
                    local.setType("image/*");
                    local.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(local, PICK_PHOTO);
                    break;
                default:
                    break;
            }
        }
    };

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch(requestCode) {
                case TAKE_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap b = (Bitmap) extras.get("data");
                    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
                    String fileNmae = Environment.getExternalStorageDirectory().toString()+ File.separator+"aurora/image/"+name+".jpg";
                    String srcPath = fileNmae;
                    File myCaptureFile =new File(fileNmae);
                    try {
                        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                            if(!myCaptureFile.getParentFile().exists()){
                                myCaptureFile.getParentFile().mkdirs();
                            }
                            BufferedOutputStream bos;
                            bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                            b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                            bos.flush();
                            bos.close();
                            Uri uri = Uri.fromFile(myCaptureFile);
                            imageUri.add(uri);
                            imageSelectAdapter.notifyDataSetChanged();
                            imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());

                        }else{

                            Toast toast= Toast.makeText(AddExpenceActivity.this, "保存失败，SD卡无效", Toast.LENGTH_SHORT);
                            toast.show();
                        }
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                case PICK_PHOTO:
                    Uri uri = data.getData();
                    imageUri.add(uri);
                    imageSelectAdapter.notifyDataSetChanged();
                    imageSelectAdapter.notifyItemRemoved(imageSelectAdapter.getItemCount());
                    break;
                default:
                    break;
            };
        }
    }

    @Override
    public AddExpenceData getExpenceData() {
        AddExpenceData addExpenceData = new AddExpenceData();
        addExpenceData.expensetype = et_expence_type.getText().toString();
        addExpenceData.money = Integer.parseInt(et_expence_money.getText().toString());
        addExpenceData.seller = et_sell.getText().toString();
        return addExpenceData;
    }

    @Override
    public void showProgress() {
        progressDialog = ProgressDialog.show(this,null,"正在发送报销...");
    }

    @Override
    public List<File> getImageFiles() {
        List<File> files = new ArrayList<>();
        for(int i = 0;i<imageUri.size();i++){
            File file =new File(UriUtils.getRealFilePath(this,imageUri.get(i)));
            files.add(file);
        }
        return files;
    }

    @Override
    public void hideProgress() {
        progressDialog.dismiss();
    }

    @Override
    public void onExpenceUploadSuccess() {
        ToastUtil.show(this,"报销信息上传成功！");
        finish();
    }

    @Override
    public void onExpenceUploadFail(String msg) {
        ToastUtil.show(this,"报销信息上传失败"+msg);
    }

    @Override
    public void onFilesUploadFail(String msg) {
        ToastUtil.show(this,"图片上传失败"+msg);

    }
}
